package com.example.web.controller;

import com.example.web.entity.Customer;
import com.example.web.entity.Result;
import com.example.web.service.CustomerService;
import com.example.web.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/api/customers")
@CrossOrigin(origins = "http://localhost:3001", allowCredentials = "true")
public class CustomerController {

    @Autowired
    private CustomerService customerService;
    
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取客户列表（支持分页和筛选）
     */
    @GetMapping
    public Result<Map<String, Object>> getCustomerList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String keyword,
            HttpServletRequest request) {
        try {
            Long creatorId = getCurrentUserId(request);
            if (creatorId == null) {
                return Result.error(401, "未认证");
            }
            
            Map<String, Object> result = customerService.getCustomerList(page, size, status, keyword, creatorId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取客户列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取客户
     */
    @GetMapping("/{id}")
    public Result<Customer> getCustomerById(@PathVariable Long id, HttpServletRequest request) {
        try {
            if (!isAuthenticated(request)) {
                return Result.error(401, "未认证");
            }
            
            Customer customer = customerService.findById(id);
            if (customer == null) {
                return Result.error(404, "客户不存在");
            }
            return Result.success(customer);
        } catch (Exception e) {
            return Result.error("获取客户信息失败: " + e.getMessage());
        }
    }

    /**
     * 创建新客户
     */
    @PostMapping
    public Result<Customer> createCustomer(@Valid @RequestBody Customer customer, HttpServletRequest request) {
        try {
            Long creatorId = getCurrentUserId(request);
            if (creatorId == null) {
                return Result.error(401, "未认证");
            }
            
            // 设置创建人
            customer.setCreatorId(creatorId);
            
            Customer createdCustomer = customerService.createCustomer(customer);
            return Result.success("客户创建成功", createdCustomer);
        } catch (Exception e) {
            return Result.error("创建客户失败: " + e.getMessage());
        }
    }

    /**
     * 更新客户信息
     */
    @PutMapping("/{id}")
    public Result<Customer> updateCustomer(@PathVariable Long id, @Valid @RequestBody Customer customer, HttpServletRequest request) {
        try {
            if (!isAuthenticated(request)) {
                return Result.error(401, "未认证");
            }
            
            customer.setId(id);
            Customer updatedCustomer = customerService.updateCustomer(customer);
            if (updatedCustomer == null) {
                return Result.error(404, "客户不存在");
            }
            return Result.success("客户更新成功", updatedCustomer);
        } catch (Exception e) {
            return Result.error("更新客户失败: " + e.getMessage());
        }
    }

    /**
     * 删除客户
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteCustomer(@PathVariable Long id, HttpServletRequest request) {
        try {
            if (!isAuthenticated(request)) {
                return Result.error(401, "未认证");
            }
            
            boolean deleted = customerService.deleteCustomer(id);
            if (!deleted) {
                return Result.error(404, "客户不存在");
            }
            return Result.success("客户删除成功", null);
        } catch (Exception e) {
            return Result.error("删除客户失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户创建的客户列表（用于互动记录的客户下拉选择）
     */
    @GetMapping("/by-creator")
    public Result<java.util.List<Customer>> getCustomersByCreator(HttpServletRequest request) {
        try {
            Long creatorId = getCurrentUserId(request);
            if (creatorId == null) {
                return Result.error(401, "未认证");
            }
            
            java.util.List<Customer> customers = customerService.getCustomersByCreator(creatorId);
            return Result.success(customers);
        } catch (Exception e) {
            return Result.error("获取客户列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取客户状态选项
     */
    @GetMapping("/status-options")
    public Result<String[]> getStatusOptions(HttpServletRequest request) {
        try {
            if (!isAuthenticated(request)) {
                return Result.error(401, "未认证");
            }
            
            String[] statusOptions = {"潜在客户", "已联系客户", "已流失"};
            return Result.success(statusOptions);
        } catch (Exception e) {
            return Result.error("获取状态选项失败: " + e.getMessage());
        }
    }

    /**
     * 检查用户是否已认证
     */
    private boolean isAuthenticated(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            if (token == null) {
                return false;
            }
            
            String username = jwtUtils.getUsernameFromToken(token);
            return jwtUtils.validateToken(token, username);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            if (token == null) {
                return null;
            }
            
            String username = jwtUtils.getUsernameFromToken(token);
            if (jwtUtils.validateToken(token, username)) {
                // 这里需要根据用户名获取用户ID，您可能需要调用UserService
                // 简化处理：从JWT中获取用户ID（如果JWT中包含用户ID）
                return jwtUtils.getUserIdFromToken(token);
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 从请求中提取Token
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}